package 多线程.Test;

/**
 * demo有问题，不应该用notifyAll
 * 唤醒其他所有线程的思路是错的，应该转变思路
 * 这样还是会导致交替执行
 */
public class ABCThreadDemo {
    private static final Object lock = new Object();

    public static void main(String[] args) {
        Thread threadA = new Thread(new AThread());
        Thread threadB = new Thread(new BThread());
        Thread threadC = new Thread(new CThread());

        threadA.start();
        threadB.start();
        threadC.start();
    }
    static class AThread implements Runnable {
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            for (int i = 0; i < 10; i++) {
                synchronized (lock) {
                    System.out.println("A ");
                    lock.notifyAll(); // 唤醒其他等待的线程
                    try {
                        lock.wait(); // 当前线程等待
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    static class BThread implements Runnable {
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            for (int i = 0; i < 10; i++) {
                synchronized (lock) {
                    System.out.println("B ");
                    lock.notifyAll(); // 唤醒其他等待的线程
                    try {
                        lock.wait(); // 当前线程等待
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    static class CThread implements Runnable {
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            for (int i = 0; i < 10; i++) {
                synchronized (lock) {
                    System.out.println("C ");
                    lock.notifyAll(); // 唤醒其他等待的线程
                    try {
                        lock.wait(); // 当前线程等待
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}


